package com.yunli.mall.service.impl;

import com.yunli.mall.common.util.IdGenUtil;
import com.yunli.mall.enums.SeckillStateEnum;
import com.yunli.mall.repository.PayOrderMapper;
import com.yunli.mall.repository.SeckillMapper;
import com.yunli.mall.schema.entity.PayOrder;
import com.yunli.mall.schema.entity.Seckill;
import com.yunli.mall.schema.response.SeckillExecution;
import com.yunli.mall.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author yaolonglong
 * @date 2020/9/21 21:03
 */

public class CasSeckillServiceImpl implements SeckillService {
    @Autowired
    private PayOrderMapper orderMapper;
    @Autowired
 private SeckillMapper seckillMapper;

    @Override
    public SeckillExecution executor(String seckillId, String phone) {
        Seckill seckill;
        while (true) {
            seckill = seckillMapper.selectById(seckillId);
            if (seckill.getInventory() < 1) {
                return new SeckillExecution(seckillId, SeckillStateEnum.ACCESS_LIMIT);
            }
            int result = seckillMapper.updateUseCAS(seckill);
            if (result == 1) {
                break;
            }
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setId(IdGenUtil.nextId());
        payOrder.setSeckillId(seckillId);
        payOrder.setUserPhone(phone);
        payOrder.setState(0);
        orderMapper.insert(payOrder);
        return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS);
    }

    @Override
    public int result(String seckillId, String phone) {
        return 0;
    }
}
